package com.riven.redisson.concurrent;

import com.riven.redisson.annotation.EnableDistributedLock;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;

/**
 * @author riven
 * @since 2025-05-22
 */
public class DistributedLockBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar {

    public static final String DEFAULT_LOCK_PROVIDER_BEAN_NAME = "defaultRedissonLockProvider";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes attributes = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableDistributedLock.class.getName()));
        //interceptor
        BeanDefinitionBuilder interceptorBuilder = BeanDefinitionBuilder.genericBeanDefinition(DistributedLockInterceptor.class);
        interceptorBuilder.addPropertyValue("order", attributes.getNumber("order"));
        interceptorBuilder.addPropertyValue("application", attributes.getString("application"));
        registry.registerBeanDefinition(DistributedLockInterceptor.class.getSimpleName(), interceptorBuilder.getBeanDefinition());

        //default lock provider
        BeanDefinitionBuilder defaultProviderBuilder = BeanDefinitionBuilder.genericBeanDefinition(SetNxRedissonLockProvider.class);
        defaultProviderBuilder.addPropertyValue("maxLockMillis", attributes.getNumber("maxLockMillis"));
        registry.registerBeanDefinition(DEFAULT_LOCK_PROVIDER_BEAN_NAME, defaultProviderBuilder.getBeanDefinition());
    }

}
